import 'dotenv/config';
import{createServer}from 'http';
const PORT=process.env.PORT;
const users=[
    {id:1,name:'张三'},
    {id:2,name:'李四'},
    {id:3,name:'王五'}
];
const logger=(req,res,next)=>{
    console.log('${req.method} ${req.url}');
    next();
};
const jsonMiddleware=(req,res,next)=>{
    res.setHeader('Content-Type','application/json;charset=utf-8');
    next();
};
const getUsersHandler=(req,res)=>{
    res.write(JSON.stringify(users));
    res.end();
};
const getUsersHandler =(req,res)=>{
    const id=req.url.split('/')[3];
    const user=users.find(user=>user.id==id);
    if(user){
        res.write(JSON.stringify(user));
    }else{
        res.statusCode=404;
        res.write(JSON.stringify({message:'用户不存在'})); 
       }
       res.end();
    };
    const notFoundHandler=(req,res)=>{
        res.statusCode=404;
        res.write(JSON.stringify({message:'API不存在'})); 
        res.end();
    };
    const createUserHandler=(req,res)=>{
        let body='';
        req.on('data',(chunk)=>{
            body+=chunk.toString();
        });
        req.on('end',()=>{
            const user=JSON.parse(body);
            users.push(user);
            res.statusCode=201;
            res.write(JSON.stringify(user));
            res.end();
        });
    };
           
    const server=createServer((req,res)=>{
        logger(req,res,()=>{
        jsonMiddleware=(req,res,()=>{
            if(req.url==='/api/users' && req.method==='GET'){
                getUsersHandler(req,res);
            }else if(req.url_startsWith('/api/users/') && req.method==='GET'){
                getUsersHandler(req,res);
            }else if(req.url==='/api/users/' && req.method==='POST'){
                createUserHandler(req,res);
            }else{
                notFoundHandler(req,res);
            }       
        })
    })
});

server.listen(PORT,()=>{
    console.log(`服务器已启动，监听端口${PORT}`);
});